import React, { useEffect, useState } from "react";
import { getAuthorDraftList } from "@/apis/userApi";
import { List, Button, Modal } from "antd";
import { useNavigate } from "react-router-dom";
import { deleteDraft } from "@/apis/draftApi";
import { AuthorDraft } from "@/apis/shared";

const UserDriftList: React.FC = () => {
  const navigate = useNavigate();

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [articleList, setArticleList] = useState<AuthorDraft[]>([]);
  const [draftIdToDelete, setDraftIdToDelete] = useState<string>("");

  // 获取草稿列表数据
  const fetchArticleListData = async () => {
    const res = await getAuthorDraftList();
    console.log(res);
    setArticleList(res.data ? res.data : []);
  };

  // 页面加载时获取草稿列表数据
  useEffect(() => {
    fetchArticleListData();
  }, []);

  // 编辑草稿逻辑
  const handleEditDraft = (draftId: string) => {
    console.log("handleEditDraft at UserDriftList", draftId);
    // 跳转到对应的draft编辑页面
    navigate(`/editor/?draftId=${draftId}`);
  };

  // 打开弹窗逻辑
  const showModal = async (draftId: string) => {
    setDraftIdToDelete(draftId);
    console.log("showModal at UserDriftList", draftId);

    // 打开弹窗
    setIsModalOpen(true);
  };

  // 确定按钮逻辑
  const handleOk = async () => {
    // 调用删除草稿接口
    const res = await deleteDraft(draftIdToDelete);

    // 设置draftIdToDelete为空
    setDraftIdToDelete("");

    // 重新加载草稿列表
    if (res.code === 200) {
      fetchArticleListData();
    }

    // 关闭弹窗
    setIsModalOpen(false);
  };

  // 取消按钮逻辑
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  return (
    <div
      style={
        {
          // maxHeight: "520px", // 设置最大高度
          // overflowY: "auto", // 启用垂直滚动条
        }
      }
    >
      {articleList.length === 0 ? (
        <div>暂无草稿</div>
      ) : (
        <List
          size="large"
          // header={<div>Header</div>}
          // footer={<div>Footer</div>}
          bordered
          dataSource={articleList ? articleList : []}
          renderItem={(item) => (
            <List.Item key={item._id} style={{ textAlign: "left" }}>
              <List.Item.Meta
                title={<a href={`/editor?draftId=${item._id}`}>{item.title}</a>}
                description={item.summary}
              />
              <Button
                type="link"
                style={{ width: "70px" }}
                onClick={() => handleEditDraft(item._id)}
              >
                编辑草稿
              </Button>
              <Button
                type="link"
                style={{ width: "70px" }}
                onClick={() => showModal(item._id)}
              >
                删除草稿
              </Button>
            </List.Item>
          )}
        />
      )}
      <Modal
        title="注意"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <p>确定要删除该草稿吗？</p>
      </Modal>
    </div>
  );
};

export default UserDriftList;
